package nobu.nakata.nfcfare.resource.mapper.strategy;

import java.util.Date;

import javax.jdo.PersistenceManager;

import net.sf.jsr107cache.Cache;
import nobu.nakata.nfcfare.datamapper.TrainStationDataMapper;
import nobu.nakata.nfcfare.datamapper.TrainStationHistoryDataMapper;
import nobu.nakata.nfcfare.resource.item.ITrainResourceItem;
import nobu.nakata.nfcfare.resource.item.impl.TrainResourceItem;
import nobu.nakata.nfcfare.resource.mapper.IPersistenceStrategy;
import nobu.nakata.nfcfare.table.TrainStation;
import nobu.nakata.nfcfare.table.TrainStationHistory;

import com.google.appengine.api.users.User;


public class TrainPersistence implements IPersistenceStrategy<ITrainResourceItem, Long> {
	private Cache cache;
	private PersistenceManager pm;
	private User viewer;
	
	private TrainStationDataMapper _stationList;
	private TrainStationHistoryDataMapper _historyList;
	
	public TrainPersistence(Cache cache, PersistenceManager pm, User viewer) {
		this.cache		= cache;
		this.pm			= pm;
		this.viewer		= viewer;
	}

	@Override
	public ITrainResourceItem get(Long key) {
		TrainStation station = getStationListGateway().findByTrainCode(key);
		if (station == null)
			return null;
		return new TrainResourceItem(key, station.getStationName());
	}

	@Override
	public void set(ITrainResourceItem item) {
		getStationHistoryGateway().set(new TrainStationHistory(
				item.getTrainCode(), item.getName(), viewer, (new Date()).getTime()));
		getStationListGateway().set(new TrainStation(item.getTrainCode(), item.getName()));
	}

	@Override
	public void remove(ITrainResourceItem item) {
		throw new RuntimeException("Not implemented yet"); 
	}

	private TrainStationDataMapper getStationListGateway() {
		if (_stationList == null)
			_stationList = new TrainStationDataMapper(cache, pm);
		return _stationList;
	}
	private TrainStationHistoryDataMapper getStationHistoryGateway() {
		if (_historyList == null)
			_historyList = new TrainStationHistoryDataMapper(cache, pm);
		return _historyList;
	}
}